import re

from users.models import User


def jwt_response_payload_handler(token,user= None,request=None):

    return {
        'token':token,
        "username":user.username,
        "user_id":user.id
    }

from django.contrib.auth.backends import ModelBackend

#代码抽取
def get_count(username):
    try:
        if re.match(r'1[345789]\d{9}', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNoExist:
        return None

    return user


class UsernameMoilbeModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # try:
        #     if re.match(r'1[345789]\d{9}', username):
        #         user = User.objects.get(mobile=username)
        #     else:
        #         user = User.objects.get(username=username)
        # except User.DoesNoExist:
        #     return None

        user = get_count(username)

        if user.check_password(password):
            return user
        else:
            return None